package com.aboo.frame.exception;

import com.aboo.frame.constant.ErrEnum;
import com.aboo.frame.vo.ReturnVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ReturnVO<Object> handler(Exception e) {
        ErrEnum err = null;
        if (e instanceof ConstraintViolationException || e instanceof MethodArgumentNotValidException) {
            err = ErrEnum.ERR_000003;
        } else {
            err = ErrEnum.ERR_000001;
        }

        ReturnVO<Object> rv = new ReturnVO<>(err);
        String exception = e.getClass().getName();
        String message = e.getMessage();
        rv.setExtend(exception + ":" + message);
        log.error("系统发生异常！", e);
        return rv;
    }

}
